/**
 * Copyright:Copyright(c)2014-2017
 * Company:厦门市易致达物联网科技有限公司
 *
 * @version 1.0
 */
package shop.controller.front.news;

import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import shop.core.FrontBaseController;
import shop.core.Services;
import shop.core.common.bean.JSONResult;
import shop.core.plugins.wxlogin.AccessToken;
import shop.core.plugins.wxlogin.WxContainer;
import shop.core.plugins.wxlogin.WxUrlType;
import shop.core.plugins.wxlogin.WxUtil;
import shop.core.util.QRcodeUtils;
import shop.core.util.StrUtils;
import shop.services.front.news.NewsService;
import shop.services.front.news.bean.News;
import shop.services.manage.system.bean.User;
import shop.services.manage.system.impl.UserService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @类名称：NewsController
 * @创建人：Wzl
 * @创建时间：2017-09-20 下午15:47:58
 * @版本号：1.0
 * @描述：资讯
 */
@Controller
@RequestMapping("/front/news/")
public class NewsController extends FrontBaseController<News> {
    @Resource
    private NewsService newsService;
    @Resource
    private UserService userService;

    @Override
    public Services<News> getService() {
        return newsService;
    }

    /**
     * 跳转到资讯首页（列表）
     *
     * @return
     */
    @RequestMapping("toNewsList")
    public String toNewsList() {
        return "/front/index";
    }

    /**
     * 跳转到资讯详情页面
     *
     * @return
     */
    @RequestMapping("toNewsDetail")
    public String toNewsDetail() {
        return "/front/news/newsDetail";
    }

    /**
     * 跳转到搜索商品页面
     *
     * @return
     */
    @RequestMapping("toSearchProductList")
    public String toSearchProductList() {
        return "/front/product/productList";
    }

    /**
     * 微信授权登陆
     *
     * @return
     */
    @RequestMapping(value = "toWx", method = RequestMethod.GET)
    public String toWx(HttpServletRequest request) {
        String pid = request.getParameter("pid");
        String appidUrl = "?appid=wx06c25223c25de31d&";
        String redirect_uri = "redirect_uri=http://agent.finebeiy.com/rest/front/news/callBack";
        String typeUrl = "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
        if (!StringUtils.isBlank(pid)) {
            redirect_uri = redirect_uri + "?pid=" + pid;
        }
        return "redirect:" + WxUrlType.authorizeUrl + appidUrl + redirect_uri + typeUrl;
    }

    /**
     * 微信回调方法
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "callBack", method = RequestMethod.GET)
    public String callBack(HttpSession session, HttpServletRequest request) {
        String pid = request.getParameter("pid");
        String code = request.getParameter("code");
        Map<String, String> params = new HashMap<>();
        params.put("appid", WxContainer.appid);
        params.put("secret", WxContainer.secret);
        params.put("code", code);
        params.put("grant_type", "authorization_code");
        AccessToken accessToken = WxUtil.sendRequest(WxUrlType.accessTokenUrl, HttpMethod.GET, params, null, AccessToken.class);
        Map<String, String> getUserInfoParams = new HashMap<>();
        getUserInfoParams.put("access_token", accessToken.getAccess_token());
        getUserInfoParams.put("openid", accessToken.getOpenid());
        getUserInfoParams.put("lang", "zh_CN");
        Map<String, String> wxReturn = WxUtil.sendRequest(WxUrlType.userInfoUrl, HttpMethod.GET, getUserInfoParams, null, Map.class);
        logger.debug("微信登陆返回信息：" + wxReturn);
        String openID = accessToken.getOpenid();
        logger.debug("userOpenId：" + openID);
        session.setAttribute("userOpenId", openID);
        User user = userService.selectByOpenId(accessToken.getOpenid());
        if (user != null) {
            session.setAttribute("userInfo", user);
            if (!StringUtils.isBlank(pid)) {
                return "redirect:/rest/front/catalog/toCatalogList";
            }else{
                return "redirect:/rest/front/news/toNewsList";
            }
        } else {
            User loginUser = new User();
            loginUser.setOpenID(wxReturn.get("openid"));
            loginUser.setNickname(wxReturn.get("nickname"));
            loginUser.setSex(String.valueOf(wxReturn.get("sex")));
            loginUser.setIcon(wxReturn.get("headimgurl"));
            loginUser.setUsername(StrUtils.getUUID());
            loginUser.setPassword(StrUtils.getUUID());
            loginUser.setRankID("1");
            loginUser.setRid("3");
            loginUser.setStatus("n");
            loginUser.setPid("0");
            userService.insert(loginUser);
            QRcodeUtils qrCodeUtils = new QRcodeUtils();
            String iconUrl = qrCodeUtils.getIconByUrl(request, loginUser.getIcon());
            String contents = "http://agent.finebeiy.com/rest/front/news/toWx?pid=" + loginUser.getId();
            loginUser.setQrCode(qrCodeUtils.createQrcode(request, contents, iconUrl));
            userService.update(loginUser);
            session.setAttribute("userInfo", loginUser);
            if (!StringUtils.isBlank(pid)) {
                return "redirect:/rest/front/catalog/toCatalogList";
            }
            return "redirect:/rest/front/news/toNewsList";
        }
    }


//    /**
//     * 微信授权登陆
//     * @return
//     */
//    @RequestMapping(value = "toWx", method = RequestMethod.GET)
//    public String toWx(HttpServletRequest request) {
//        String pid=request.getParameter("pid");
//        String mid=request.getParameter("mid");
//        String appidUrl = "?appid=wx64245f0912483f51&";
//        String redirect_uri = "redirect_uri=http://www.pinrenzheng.cn/rest/front/news/callBack";
//        String typeUrl = "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
//        if(!StringUtils.isBlank(pid)){
//            if(!StringUtils.isBlank(mid)){
//                redirect_uri=redirect_uri+"?pid="+pid+"_"+mid;
//            }else{
//                redirect_uri=redirect_uri+"?pid="+pid;
//            }
//        }
//        return "redirect:" + WxUrlType.authorizeUrl + appidUrl + redirect_uri + typeUrl;
//    }


//    /**
//     * 微信回调方法
//     * @param request
//     * @return
//     */
//    @RequestMapping(value = "callBack", method = RequestMethod.GET)
//    public String callBack(HttpSession session, HttpServletRequest request) {
//        String uid = request.getParameter("pid");
//        String pid = "";
//        String mid = "";
//        if (!StringUtils.isBlank(uid)) {
//            if (uid.contains("_")) {
//                pid = uid.substring(0, uid.indexOf("_"));
//                mid = uid.substring(uid.indexOf("_") + 1);
//            } else {
//                pid = uid;
//            }
//        }
//        String code = request.getParameter("code");
//        Map<String, String> params = new HashMap<>();
//        params.put("appid", WxContainer.appid);
//        params.put("secret", WxContainer.secret);
//        params.put("code", code);
//        params.put("grant_type", "authorization_code");
//        AccessToken accessToken = WxUtil.sendRequest(WxUrlType.accessTokenUrl, HttpMethod.GET, params, null, AccessToken.class);
//        Map<String, String> getUserInfoParams = new HashMap<>();
//        getUserInfoParams.put("access_token", accessToken.getAccess_token());
//        getUserInfoParams.put("openid", accessToken.getOpenid());
//        getUserInfoParams.put("lang", "zh_CN");
//        Map<String, String> wxReturn = WxUtil.sendRequest(WxUrlType.userInfoUrl, HttpMethod.GET, getUserInfoParams, null, Map.class);
//        logger.debug("微信登陆返回信息：" + wxReturn);
//        String openID = accessToken.getOpenid();
//        logger.debug("userOpenId：" + openID);
//        session.setAttribute("userOpenId", openID);
//        User user = userService.selectByOpenId(accessToken.getOpenid());
//        String url = bindSub(session, request, wxReturn, user, pid, mid);
//        return url;
//    }
//
//    /**
//     * 绑定下级用户并跳转到相应页面
//     *
//     */
//    private String bindSub(HttpSession session, HttpServletRequest request, Map<String, String> wxReturn, User user, String pid, String mid) {
//        if (user != null) {
//            if (!StringUtils.isBlank(pid) && StringUtils.isBlank(user.getPid())) {
//                if (StringUtils.isBlank(mid)) {
//                    user.setPid(pid);
//                    userService.update(user);
//                    session.setAttribute("userInfo", user);
//                    return "redirect:/rest/front/user/toSellerMyStore?id=" + user.getPid();
//                } else {
//                    user.setPid(pid);
//                    userService.update(user);
//                    session.setAttribute("userInfo", user);
//                    return "redirect:/rest/front/product/toProductDetail?id=" + mid;
//                }
//            } else {
//                session.setAttribute("userInfo", user);
//                return "redirect:/rest/front/news/toNewsList";
//            }
//        } else {
//            User loginUser = new User();
//            loginUser.setOpenID(wxReturn.get("openid"));
//            loginUser.setNickname(wxReturn.get("nickname"));
//            loginUser.setSex(String.valueOf(wxReturn.get("sex")));
//            loginUser.setIcon(wxReturn.get("headimgurl"));
//            loginUser.setUsername(StrUtils.getUUID());
//            loginUser.setPassword(StrUtils.getUUID());
//            loginUser.setRid("3");
//            loginUser.setStatus("n");
//            if (!StringUtils.isBlank(pid)) {
//                loginUser.setPid(pid);
//                userService.insert(loginUser);
//                QRcodeUtils qrCodeUtils = new QRcodeUtils();
//                String contents = "http://www.pinrenzheng.cn/rest/front/news/toWx?pid=" + loginUser.getId();
//                loginUser.setQrCode(qrCodeUtils.createQrcode(request, contents));
//                userService.update(loginUser);
//                session.setAttribute("userInfo", loginUser);
//                if (StringUtils.isBlank(mid)) {
//                    return "redirect:/rest/front/user/toSellerMyStore?id=" + loginUser.getPid();
//                } else {
//                    return "redirect:/rest/front/product/toProductDetail?id=" + mid;
//                }
//            } else {
//                userService.insert(loginUser);
//                QRcodeUtils qrCodeUtils = new QRcodeUtils();
//                String contents = "http://www.pinrenzheng.cn/rest/front/news/toWx?pid=" + loginUser.getId();
//                loginUser.setQrCode(qrCodeUtils.createQrcode(request, contents));
//                userService.update(loginUser);
//                session.setAttribute("userInfo", loginUser);
//                return "redirect:/rest/front/news/toNewsList";
//            }
//        }
//    }


    /**
     * 获取缓存用户信息
     *
     * @param session
     * @return
     */
    @RequestMapping(value = "getSession", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult getSession(HttpSession session) {
        JSONResult rs = new JSONResult();
        Map result = new HashMap<>();
        if (session.getAttribute("userInfo") != null) {
            result.put("user", session.getAttribute("userInfo"));
        } else {
            result.put("user", null);
        }
        rs.setData(result);
        rs.setSuccess(true);
        return rs;
    }

    /**
     * 更新缓存用户信息
     *
     * @param session
     * @return
     */
    @RequestMapping(value = "updateSession", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult updateSession(HttpSession session) {
        JSONResult rs = new JSONResult();
        Map result = new HashMap<>();
        if (session.getAttribute("userInfo") != null) {
            User user = (User) session.getAttribute("userInfo");
            user = userService.selectById(user.getId());
            session.setAttribute("userInfo", user);
            result.put("user", session.getAttribute("userInfo"));
        } else {
            result.put("user", null);
        }
        rs.setData(result);
        rs.setSuccess(true);
        return rs;
    }

    @Override
    public JSONResult insertJson(HttpServletRequest request, @ModelAttribute("e") News news) throws Exception {
        return null;
    }

    @Override
    public JSONResult updateJson(HttpServletRequest request, @ModelAttribute("e") News news) throws Exception {
        return null;
    }

    @Override
    public JSONResult deleteJson(HttpServletRequest request, @ModelAttribute("e") News news) throws Exception {
        return null;
    }
}
